package puzzle.projecteuler.p100;

public class Problem044 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int max = 100000;
		for (int i = 1; i < max; i ++) {
			long pi = p(i);
			/*
			 *    pj - pk = pi >= p(k+1)-p(k) = 3k+1
			 * => k <= (pi-1)/3
			 *    
			 *    pj + pk = 2*pk + pi
			 */
			for (int k = 1; k <= (pi-1)/3; k ++) {
				long pk = p(k);
				if (isPentagonal(pk+pi) && isPentagonal(2*pk+pi)) {
					System.out.println(pi);
					return;
				}
			}
		}
	}

	public static long p(int n) {
		return n*(3*n-1)/2;
	}

	public static boolean isPentagonal(long m) {
		long t = 24*m+1;
		int n = (int)(Math.sqrt(t)+1)/6;
		return m == p(n);
	}
}
